package admin

import (
	"fmt"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	"math/rand"
	"net"
	"os"
	"path/filepath"
	"runtime"
	"strconv"
	"strings"
	"tcsc/controllers/pc"
	"tcsc/models"
	"tcsc/sword"
	"time"
)

type Index struct {
	BaseController
}

func (c *Index) Get() {
	now := time.Now().Local()
	nows := now.Format(`2006-01-02`)
	nows += ` 00:00:00`
	c.Data["mcount"] = models.Query("select count(*) as count from mt_member where status=1")[0]["count"]
	c.Data["scount"] = models.Query("select count(*) as count from mt_shop where status=1")[0]["count"]
	c.Data["mcountn"] = models.Query("select count(*) as count from mt_member where status=1 and addtime>'" + nows + "'")[0]["count"]
	c.Data["pcount"] = models.Query("select count(*) as count from mt_product where status=1")[0]["count"]
	c.Data["ncount"] = models.Query("select count(*) as count from mt_news where status=1")[0]["count"]
	where := " b.gid=" + c.Gid
	if c.Gid == "0" {
		shop := models.Query(`select id from mt_shop where status=1 and censoring=1 and style=0`)
		var gid []string
		gid = append(gid, "0")
		for _, v := range shop {
			gid = append(gid, v["id"].(string))
		}
		gids := strings.Join(gid, ",")
		where = " b.gid in(" + gids + ")"
	}
	read := models.Query(`select a.* from mt_systems_reading a 
		left join mt_product b on b.id=a.pid
		where ` + where + `
		order by a.addtime desc limit 0,10`)
	if read != nil {
		for _, v := range read {
			v["member"] = models.Query(`select a.id,a.monicker,a.country,a.mobile,b.pathname,a.province,a.city from mt_member a 
				left join mt_resources b on a.avatar=b.id where a.id=` + v["uid"].(string))[0]
			gid, ok := v["gid"].(string)
			if ok {
				g := models.Query(`select name from mt_shop where id=` + gid)
				v["name"] = g[0]["name"]
				v["type"] = "店铺"
				v["url"] = `/admin/shop/content?id=` + gid
			} else {
				xid, ok := v["xid"].(string)
				if ok {
					w := models.Query(`select title from mt_news where id=` + xid)
					v["name"] = w[0]["title"]
					v["type"] = "新闻"
					v["url"] = `/admin/news/content?id=` + xid
				} else {
					pid, ok := v["pid"].(string)
					if ok {
						g := models.Query(`select title from mt_product where id=` + pid)
						v["name"] = g[0]["title"]
						v["type"] = "产品"
						v["url"] = `/admin/product/content?id=` + pid
					}
				}
			}
		}
	}
	c.Data["read"] = read
	c.Data["goversion"] = runtime.Version()
	c.Data["system"] = models.Systems()
	c.Data["OS"] = runtime.GOOS
	c.Data["hostname"], _ = os.Hostname()
	addrs, err := net.InterfaceAddrs()
	if err != nil {
		beego.Debug(err)
		os.Exit(1)
	}
	for _, address := range addrs {
		if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
			if ipnet.IP.To4() != nil {
				c.Data["ip"] = ipnet.IP.String()
			}

		}
	}
	//h := syscall.MustLoadDLL("kernel32.dll")
	//d := h.MustFindProc("GetDiskFreeSpaceExW")
	//lpFreeBytesAvailable := int64(0)
	//lpTotalNumberOfBytes := int64(0)
	//lpTotalNumberOfFreeBytes := int64(0)
	//_, _, err = d.Call(uintptr(unsafe.Pointer(syscall.StringToUTF16Ptr("C:"))), uintptr(unsafe.Pointer(&lpFreeBytesAvailable)), uintptr(unsafe.Pointer(&lpTotalNumberOfBytes)), uintptr(unsafe.Pointer(&lpTotalNumberOfFreeBytes)))
	//c.Data["f"] = lpTotalNumberOfFreeBytes / 1024 / 1024
	c.Data["dir"], _ = filepath.Abs(filepath.Dir(os.Args[0]))
	c.Data["mysqlv"] = models.Query("select version()")[0]["version()"].(string)
	c.TplName = "admin/index/index.html"
}

type IndexChart struct {
	BaseController
}

func (c *IndexChart) Get() {
	id := c.Gid
	shopid := c.GetString("shop")
	if shopid != "" {
		id = shopid
		c.Data["shopid"] = shopid
		if shopid != "0" {
			c.Data["productCount"] = models.Query(`select count(id) as totals from mt_product 
				where status=1 and censoring=1 and gid=?`, shopid)[0]["totals"]
			c.Data["vipCount"] = models.Query(`select count(a.id) as totals from mt_member_vip_order a 
				left join mt_member_vip b on a.vid=b.id 
				where b.status=1 and b.gid=?`, shopid)[0]["totals"]
		}
	}
	var pid []string
	var psql string
	if id == "0" {
		psql = `select a.id from mt_product a left join mt_shop b on a.gid=b.id where a.status=1 and a.censoring=1 and (a.gid=0 or b.style=0)`
	} else {
		psql = `select id from mt_product where status=1 and censoring=1 and gid=` + id
	}
	product := models.Query(psql)
	for _, v := range product {
		pid = append(pid, v["id"].(string))
	}
	pids := strings.Join(pid, ",")
	if pids == "" {
		pids = "''"
	}
	now := time.Now().Local()
	week := int(now.Weekday())
	var weektime []string
	for i := 1; i <= week; i++ {
		count := week - i
		weeks := now.AddDate(0, 0, -count)
		weektime = append(weektime, weeks.Format("2006-01-02")+" 00:00:00")
	}
	var rnum []string
	var onum []string
	var mnum []string
	var ts []string
	loc, _ := time.LoadLocation("Local")
	for _, v := range weektime {
		ttime, _ := time.ParseInLocation(Tparse, v, loc)
		ts = append(ts, ttime.Format(`01-02`))
		dtime := ttime.AddDate(0, 0, 1)
		v2 := dtime.Format("2006-01-02") + ` 00:00:00`
		rnumi := models.Query(`select count(a.id) as num from mt_systems_reading a where (a.gid=` + id + ` or pid in(` + pids + `))` + `
					 and a.addtime>='` + v + `' and a.addtime<'` + v2 + `'`)[0]["num"]
		rnum = append(rnum, rnumi.(string))
		order := models.Query(`select count(a.id) as num,sum(a.money) as money from mt_order a where a.gid=` + id + ` and a.paytime>=
				'` + v + `' and a.paytime<'` + v2 + `'`)[0]
		onumi := order["num"]
		onum = append(onum, onumi.(string))
		mnumi, ok := order["money"].(string)
		if !ok {
			mnumi = "0.00"
		}
		mnum = append(mnum, mnumi)
	}
	c.Data["ts"] = ts
	c.Data["rnum"] = rnum
	c.Data["onum"] = onum
	c.Data["mnum"] = mnum
	c.Data["shop"] = models.Query(`select id,name from mt_shop where style=1 and status=1 and censoring=1`)
	c.TplName = "admin/index/chart.html"
}

type IndexRead struct {
	BaseController
}

func (c *IndexRead) Get() {
	page, page2, num := models.Pagechange(c.GetString("page"), "")
	where := " b.gid=" + c.Gid
	if c.Gid == "0" {
		shop := models.Query(`select id from mt_shop where status=1 and censoring=1 and style=0`)
		var gid []string
		gid = append(gid, "0")
		for _, v := range shop {
			gid = append(gid, v["id"].(string))
		}
		gids := strings.Join(gid, ",")
		where = " b.gid in(" + gids + ")"
	}
	sql := `select a.* from mt_systems_reading a 
		left join mt_product b on b.id=a.pid
		where ` + where + `
		order by a.addtime desc limit ` + page + `,` + num
	sql2 := `select count(a.id) as totals from mt_systems_reading a
		left join mt_product b on b.id=a.pid
		where ` + where
	read := models.Query(sql)
	if read != nil {
		for _, v := range read {
			v["member"] = models.Query(`select a.id,a.monicker,a.country,a.mobile,b.pathname,a.province,a.city from mt_member a 
				left join mt_resources b on a.avatar=b.id where a.id=` + v["uid"].(string))[0]
			gid, ok := v["gid"].(string)
			if ok {
				g := models.Query(`select name from mt_shop where id=` + gid)
				v["name"] = g[0]["name"]
				v["type"] = "店铺"
				v["url"] = `/admin/shop/content?id=` + gid
			} else {
				xid, ok := v["xid"].(string)
				if ok {
					w := models.Query(`select title from mt_news where id=` + xid)
					v["name"] = w[0]["title"]
					v["type"] = "新闻"
					v["url"] = `/admin/news/content?id=` + xid
				} else {
					pid, ok := v["pid"].(string)
					if ok {
						g := models.Query(`select title from mt_product where id=` + pid)
						v["name"] = g[0]["title"]
						v["type"] = "产品"
						v["url"] = `/admin/product/content?id=` + pid
					}
				}
			}
		}
	}
	c.Data["read"] = read
	c.Data["read"] = read
	c.Data["paginator"] = models.Page(sql2, page2, num)
	c.Data["url"] = `/admin/index/read?`
	c.TplName = "admin/index/read.html"
}

type IndexAd struct {
	BaseController
}

func (c *IndexAd) Get() {
	platform := models.Query(`select * from mt_systems_configuration where alias='platform' and status=1`)
	c.Data["platform"] = platform
	page, page2, num := models.Pagechange(c.GetString("page"), "")
	var w []string
	w = append(w, `a.status=1`)
	pid := c.GetString("pid")
	c.Data["pid"] = pid
	if pid != "" {
		w = append(w, `a.platform=`+pid)
	}
	ws := strings.Join(w, ` and `)
	lt := ` limit ` + page + `,` + num
	ob := ` order by a.addtime desc,a.sort desc`
	sql := `select a.*,b.name as pname,d.name as cname,c.pathname from mt_ad a left join mt_resources c 
	on a.img=c.id left join mt_systems_configuration b on a.platform=b.id left Join mt_systems_configuration d 
	on a.channel=d.id where ` + ws + ob + lt
	sql2 := `select count(a.id) as totals from mt_ad a where ` + ws
	info := models.Query(sql)
	c.Data["info"] = info
	c.Data["paginator"] = models.Page(sql2, page2, num)
	c.Data["url"] = `/admin/index/ad?pid=` + pid + `&`
	c.TplName = "admin/index/ad.html"
}

type IndexAdHelp struct {
	BaseController
}

func (c *IndexAdHelp) Get() {
	c.TplName = "admin/index/ad_help.html"
}

type IndexAdAE struct {
	BaseController
}

func (c *IndexAdAE) Get() {
	platform := models.Query(`select * from mt_systems_configuration where alias='platform' and status=1`)
	c.Data["platform"] = platform
	c.Data["channel"] = models.Query(`select * from mt_systems_configuration where alias='channel' and status=1`)
	id := c.GetString("id")
	if id != "" {
		c.Data["info"] = models.Query(`select a.*,b.pathname from mt_ad a left join mt_resources b on a.img=b.id where a.id=` + id)[0]
	}
	c.TplName = "admin/index/ad_ae.html"
}
func (c *IndexAdAE) Post() {
	defer c.ServeJSON()
	input := c.Input()
	if input.Get("id") == "" {
		input.Set("addtime", sword.Gettimes("2006-01-02 15:04:05"))
	}
	if res, err := models.Save("mt_ad", input); err != nil {
		beego.Debug(err)
		c.Data["json"] = 0
	} else {
		c.Data["json"] = 1
		var r models.Mt_systems_record
		r.Tid = int(res)
		if input.Get("id") == "" {
			r.Way = 2
		} else {
			r.Way = 3
		}
		r.Addtime = sword.Timeget()
		r.Table = 11
		r.Uid, _ = strconv.Atoi(c.Qid)
		if _, err := models.Orm().Insert(&r); err != nil {
			beego.Debug(err)
		}
	}
}

type IndexKeyword struct {
	BaseController
}

func (c *IndexKeyword) Get() {
	page, page2, num := models.Pagechange(c.GetString("page"), "")
	var w []string
	w = append(w, `a.status=1`)
	t := c.GetString("t")
	c.Data["t"] = t
	if t != "" {
		w = append(w, `a.type=`+t)
	}
	ws := strings.Join(w, ` and `)
	ob := ` order by a.addtime desc`
	lt := ` limit ` + page + `,` + num
	sql := `select a.* from mt_keywords a where ` + ws + ob + lt
	sql2 := `select count(a.id) as totals from mt_keywords a where a.status=1`
	info := models.Query(sql)
	c.Data["info"] = info
	c.Data["paginator"] = models.Page(sql2, page2, num)
	c.Data["url"] = `/admin/index/keyword?t=` + t + `&`
	c.TplName = "admin/index/keyword.html"
}

type IndexKeywordAE struct {
	BaseController
}

func (c *IndexKeywordAE) Get() {
	id := c.GetString("id")
	if id != "" {
		c.Data["info"] = models.Query(`select a.* from mt_keywords a where a.id=` + id)[0]
	}
	c.TplName = "admin/index/keyword_ae.html"
}

func (c *IndexKeywordAE) Post() {
	defer c.ServeJSON()
	input := c.Input()
	if input.Get("id") == "" {
		input.Set("addtime", sword.Gettimes("2006-01-02 15:04:05"))
	} else {
		input.Set("modificationtime", sword.Gettimes("2006-01-02 15:04:05"))
	}
	if res, err := models.Save("mt_keywords", input); err != nil {
		beego.Debug(err)
		c.Data["json"] = 0
	} else {
		c.Data["json"] = 1
		var r models.Mt_systems_record
		r.Tid = int(res)
		if input.Get("id") == "" {
			r.Way = 2
		} else {
			r.Way = 3
		}
		r.Addtime = sword.Timeget()
		r.Table = 12
		r.Uid, _ = strconv.Atoi(c.Qid)
		if _, err := models.Orm().Insert(&r); err != nil {
			beego.Debug(err)
		}
	}
}

type IndexFeedback struct {
	BaseController
}

func (c *IndexFeedback) Get() {
	page, page2, num := models.Pagechange(c.GetString("page"), "")
	var w []string
	w = append(w, `a.status=1`)
	if c.Gid != "0" {
		w = append(w, `a.gid=`+c.Gid)
	}

	ws := strings.Join(w, ` and `)
	ob := ` order by a.addtime desc`
	lt := ` limit ` + page + `,` + num
	sql := `select a.*,b.name from mt_feedback a left join mt_shop b on a.gid=b.id where ` + ws + ob + lt
	sql2 := `select count(a.id) as totals from mt_feedback a where ` + ws
	info := models.Query(sql)
	c.Data["info"] = info
	c.Data["paginator"] = models.Page(sql2, page2, num)
	c.Data["url"] = `/admin/index/feedback?`
	c.TplName = "admin/index/feedback.html"
}

type IndexFeedbackAE struct {
	BaseController
}

func (c *IndexFeedbackAE) Get() {
	id := c.GetString("id")
	if id != "" {
		c.Data["info"] = models.Query(`select a.* from mt_feedback a where a.id=` + id)[0]
	}
	c.TplName = "admin/index/feedback_ae.html"
}

func (c *IndexFeedbackAE) Post() {
	defer c.ServeJSON()
	input := c.Input()
	if input.Get("id") == "" {
		input.Set("addtime", sword.Gettimes("2006-01-02 15:04:05"))
	}
	input.Set("gid", c.Gid)
	if res, err := models.Save("mt_feedback", input); err != nil {
		beego.Debug(err)
		c.Data["json"] = 0
	} else {
		c.Data["json"] = 1
		var r models.Mt_systems_record
		r.Tid = int(res)
		if input.Get("id") == "" {
			r.Way = 2
		} else {
			r.Way = 3
		}
		r.Addtime = sword.Timeget()
		r.Table = 74
		r.Uid, _ = strconv.Atoi(c.Qid)
		if _, err := models.Orm().Insert(&r); err != nil {
			beego.Debug(err)
		}
	}
}

type Message struct {
	beego.Controller
}

func (c *Message) Get() {
	// c.SetSession("pc", "7")
	sess := c.GetSession("pc")
	if sess == nil {
		c.Ctx.Redirect(302, "/login")
	}
	var info []orm.Params
	uid := sess.(string)
	gid := c.GetString("gid")
	var sidd = ""
	if gid != "" {
		if gid == "0" {
			var sids []string
			if sidd == "" || sidd == "<nil>" || sidd == "0" {
				service := models.Query(`select id from mt_member where service=1 and gid=0`)
				for _, v := range service {
					sids = append(sids, v["id"].(string))
				}
			}
			for _, v := range sids {
				if is := models.Query(`select id from mt_sms where (uid=` + uid + ` and fid=` + v + `) or (fid=` + uid + ` and uid=` + v + `)`); is != nil {
					sidd = v
					models.Exec(`update mt_member set sid=` + sidd + ` where id=` + uid)
					break
				}
			}
			if sidd == "" || sidd == "<nil>" || sidd == "0" {
				r := rand.New(rand.NewSource(time.Now().UnixNano()))
				sidd = sids[r.Intn(len(sids))]
			}
			if sidd == "" || sidd == "<nil>" || sidd == "0" {
				sidd = fmt.Sprint(models.Systems()["uid"])
			}
		} else {
			var sids []string
			service := models.Query(`select id from mt_member where gid=` + gid + ` and service=1`)
			for _, v := range service {
				sids = append(sids, v["id"].(string))
			}
			for _, v := range sids {
				if is := models.Query(`select id from mt_sms where (uid=` + uid + ` and fid=` + v + `) or (fid=` + uid + ` and uid=` + v + `)`); is != nil {
					sidd = v
					break
				}
			}
			if sidd == "" {
				if len(sids) > 0 {
					r := rand.New(rand.NewSource(time.Now().UnixNano()))
					sidd = sids[r.Intn(len(sids))]
				}
			}
			if sidd == "" {
				sidd = models.Query(`select uid from mt_shop where id=` + gid)[0]["uid"].(string)
			}
		}
		if sidd == "" {
			sidd = "7"
		}
		issms := models.Query(`select id from mt_sms where (uid=? and fid=?) or (uid=? and fid=?)`, uid, sidd, sidd, uid)

		if issms == nil {
			var info1 = make(orm.Params)
			info1["fid"] = uid
			info1["uid"] = sidd
			info = append(info, info1)
		}
	}
	sql := `select * from mt_sms where id in (select max(a.id) from mt_sms a where (fid=` + uid + ` or uid=` + uid + `) and uid<>0 and fid<>0 and status=1 group by (a.fid+a.uid)) order by addtime desc`
	info2 := models.Query(sql)
	var id string
	lt := ` limit 0,20`
	for _, v := range info2 {
		info = append(info, v)
	}
	uidi, _ := strconv.Atoi(uid)
	sidi, _ := strconv.Atoi(sidd)
	idsums := uidi + sidi
	var index = 0
	for k, v := range info {
		fid := v["fid"].(string)
		sid := v["uid"].(string)
		if uid == fid {
			v["member"] = models.Query(`select a.monicker,b.pathname,a.id,a.country,a.province,a.city from mt_member a left join mt_resources b on a.avatar=b.id where a.id=` + sid)[0]
			id = sid
		} else {
			v["member"] = models.Query(`select a.monicker,b.pathname,a.id,a.country,a.province,a.city from mt_member a left join mt_resources b on a.avatar=b.id where a.id=` + fid)[0]
			id = fid
		}
		fidi, _ := strconv.Atoi(fid)
		sidi, _ := strconv.Atoi(sid)
		idsum := fidi + sidi
		if idsum == idsums {
			index = k
		}
		if k == 0 {
			if err := models.Exec(fmt.Sprintf("update mt_sms set state=1 where uid=%v and fid+uid=%v", uid, sword.Sum(id, uid))); err != nil {
				beego.Debug("打开聊天详情设为已读失败：", err)
			}
			readlast := models.Query(`
					select b.title,c.pathname,b.id,a.addtime 
					from mt_systems_reading a 
					left join mt_product b on a.pid=b.id 
					left join mt_resources c on c.id=b.img
					where a.uid=? 
					order by a.addtime desc`, sid)
			if readlast != nil {
				v["readlast"] = readlast[0]
			}
		}
		v["noread"] = models.Query(fmt.Sprintf(`select count(*) as num from mt_sms where uid+fid=%v and uid=%v and state=0 and status=1`, idsum, uid))[0]["num"]
		sql2 := `select a.* from (select * from mt_sms where (uid=` + id + ` and fid=` + uid + `) or
		 (uid=` + uid + ` and fid=` + id + `) order by id desc ` + lt + `) a order by a.id`
		info2 := models.Query(sql2)
		v["first"] = models.Query(`select a.monicker,a.id,b.pathname from mt_member a left join mt_resources b on a.avatar=b.id where a.id=` + uid)[0]
		v["second"] = models.Query(`select a.monicker,a.id,b.pathname from mt_member a left join mt_resources b on a.avatar=b.id where a.id=` + id)[0]
		v["info"] = info2
	}
	c.Data["json"] = info
	c.Data["uid"] = uid
	c.Data["index"] = index
	isservice := 0
	iss := models.Query(`select id from mt_member where id=? and service=1`, uid)
	if iss != nil {
		isservice = 1
	}
	isshop := models.Query(`select id from mt_shop where status=1 and censoring=1 and uid=?`, uid)
	if isshop != nil {
		isservice = 1
	}
	c.Data["isservice"] = isservice
	c.TplName = "admin/service/index.html"
}

type MessageUserInfo struct {
	beego.Controller
}

func (c *MessageUserInfo) Get() {
	defer c.ServeJSON()
	var js = make(map[string]interface{})
	c.Data["json"] = &js
	uid := c.GetString("uid")
	js["mem"] = models.Query(`
		select a.monicker,a.country,a.province,a.city 
		from mt_member a 
		where a.id=?`, uid)[0]
	readlast := models.Query(`
					select b.title,c.pathname,b.id,a.addtime 
					from mt_systems_reading a 
					left join mt_product b on a.pid=b.id 
					left join mt_resources c on c.id=b.img
					where a.uid=? 
					order by a.addtime desc`, uid)
	if readlast != nil {
		js["info"] = readlast[0]
		js["status"] = 1
	} else {
		js["status"] = 0
	}
	if sess := c.GetSession("pc"); sess != nil {
		uuid := sess.(string)
		uuuid := sword.Sum(uid, uuid)
		if err := models.Exec(`update mt_sms set state=1 where uid=? and fid+uid=?`, uuid, uuuid); err != nil {
			beego.Debug(err)
		}
	}
}

type Getavatar struct {
	beego.Controller
}

func (c *Getavatar) Get() {
	leftid := c.GetString("leftid")
	rightid := c.GetString("rightid")
	var js = make(map[string]interface{})
	lm := models.Query(`select a.monicker,b.pathname from mt_member a left join mt_resources b on a.avatar=b.id where a.id=` + leftid)[0]
	js["lpath"] = lm["pathname"]
	js["monicker"] = lm["monicker"]
	js["rpath"] = models.Query(`select b.pathname from mt_member a left join mt_resources b on a.avatar=b.id where a.id=` + rightid)[0]["pathname"]
	c.Data["json"] = js
	c.ServeJSON()
}

func (c *Message) Post() {
	uid := c.GetSession("pc").(string)
	id := c.GetString("id")
	page, _, num := models.Pagechange(c.GetString("page"), "20")
	lt := ` limit ` + page + `,` + num
	sql := `select a.* from (select * from mt_sms where (uid=` + id + ` and fid=` + uid + `) or
		 (uid=` + uid + ` and fid=` + id + `) order by id desc ` + lt + `) a order by a.id`
	info := models.Query(sql)
	right := models.Query(`select b.pathname from mt_member a left join mt_resources b on a.avatar=b.id where a.id=` + uid)[0]["pathname"]
	left := models.Query(`select b.pathname from mt_member a left join mt_resources b on a.avatar=b.id where a.id=` + id)[0]["pathname"]
	var js = make(map[string]interface{})
	js["info"] = info
	js["right"] = right
	js["left"] = left
	c.Data["json"] = js
	c.ServeJSON()
}

type ClearCache struct {
	beego.Controller
}

func (c *ClearCache) Get() {
	defer c.ServeJSON()
	if err := pc.Bm.ClearAll(); err != nil {
		beego.Debug(err)
		c.Data["json"] = 0
	} else {
		c.Data["json"] = 1
	}
}

type Login struct {
	beego.Controller
}

func (c *Login) Get() {
	c.TplName = "admin/login.html"
}

type Nopermission struct {
	beego.Controller
}

func (c *Nopermission) Get() {
	c.TplName = "admin/nopermissions.html"
}

func (c *Login) Post() {
	defer c.ServeJSON()
	var js = make(map[string]interface{})
	c.Data["json"] = &js
	username := c.GetString("username")
	password := c.GetString("password")
	password = sword.ToMD5(password)
	if is := models.Query(`select id,gid from mt_systems_admin where accountnumber='` + username + `' and password='` + password + `' and status=1 and censoring=1`); is != nil {
		c.SetSession("admin", fmt.Sprint(is[0]["id"]))
		js["status"] = 1
		js["gid"] = fmt.Sprint(is[0]["gid"])
	} else {
		js["status"] = 0
	}
}

type IndexHotCity struct {
	BaseController
}

func (c *IndexHotCity) Get() {
	page, page2, num := models.Pagechange(c.GetString("page"), "")
	search := c.GetString("search")
	w := ` where a.status=1 and a.style=1 and a.censoring=1`
	if search != "" {
		w += ` and b.name like '%` + search + `%'`
	}
	lt := ` limit ` + page + `,` + num
	cities := models.Query(`select a.id,a.hot,b.name from mt_shop a left join mt_area b on a.city=b.code` + w + lt)
	sql2 := `select count(a.id) as totals from mt_shop a left join mt_area b on a.city=b.code` + w + lt
	c.Data["info"] = cities
	c.Data["paginator"] = models.Page(sql2, page2, num)
	c.TplName = "admin/index/hot_city.html"
}

type IndexChangeHotCity struct {
	BaseController
}

func (c *IndexChangeHotCity) Get() {
	defer c.ServeJSON()
	id := c.GetString("id")
	table := c.GetString("table")
	json := make(map[string]interface{})
	c.Data["json"] = &json
	if err := models.Exec(`update ` + table + ` set hot=abs(hot-1) where id=` + id); err != nil {
		beego.Debug(err)
		json["status"] = 0
		return
	}
	json["status"] = 1
}

type IndexAppPush struct {
	BaseController
}

func (c *IndexAppPush) Get() {
	page, page2, num := models.Pagechange(c.GetString("page"), "10")
	table := models.Query(`select * from mt_systems_admin where status=1`)
	uid := c.GetString("uid")
	stime := c.GetString("stime")
	etime := c.GetString("etime")
	var w []string
	w = append(w, `a.status=1`)
	if uid != "" {
		w = append(w, `a.uid=`+uid)
	}
	if stime != "" {
		w = append(w, `a.create_time>'`+stime+` 00:00:00`+`'`)
	}
	if etime != "" {
		w = append(w, `a.create_time<='`+etime+` 00:00:00`+`'`)
	}
	ws := strings.Join(w, ` and `)
	lt := ` limit ` + page + `,` + num
	ob := ` order by a.create_time desc`
	appPush := models.Query(`select a.*,b.accountnumber,b.avatar from push_record a left join mt_systems_admin b on a.uid=b.id where ` + ws + ob + lt)
	for _, v := range appPush {
		if v["avatar"] != nil {
			v["pathname"] = models.Query(`select pathname from mt_resources where id=` + v["avatar"].(string))[0]["pathname"]
		}
		var userArr []string
		if v["user_group"] != nil {
			var user = models.Query(`select monicker from mt_member where id in (` + v["user_group"].(string) + `)`)
			for _, v := range user {
				if v["monicker"] != nil {
					userArr = append(userArr, v["monicker"].(string))
				}
			}
			v["user_name"] = strings.Join(userArr, ",")
		}

	}
	totals := models.Page(`select count(a.id) as totals from push_record a where `+ws, page2, num)
	c.Data["paginator"] = totals

	c.Data["info"] = appPush
	c.Data["table"] = table
	c.Data["sysId"] = uid
	c.TplName = "admin/index/app_push.html"
}

type IndexAppPushAdd struct {
	BaseController
}

func (c *IndexAppPushAdd) Get() {
	var w []string
	w = append(w, `a.status=1`)
	if c.GetString("id") != "" {
		w = append(w, `a.id=`+c.GetString("id"))
	} else {
		w = append(w, `a.id=0`)
	}

	ws := strings.Join(w, ` and `)
	appPush := models.Query(`select a.*,b.accountnumber,b.avatar from push_record a left join mt_systems_admin b on a.uid=b.id where ` + ws)
	if appPush != nil {
		c.Data["info"] = appPush[0]
	} else {
		c.Data["info"] = make(map[string]interface{})
	}
	beego.Debug(c.Data["info"])
	c.Data["member"] = models.Query(`select id,monicker,name from mt_member where status=1`)
	c.TplName = "admin/index/app_push_ae.html"
}
func (c *IndexAppPushAdd) Post() {
	defer c.ServeJSON()
	input := c.Input()
	input.Set("create_time", time.Now().Local().Format("2006-01-02 15:04:05"))
	input.Set("user_group", strings.Replace(strings.Trim(strings.Join(c.GetStrings("uid"), ","), ","), ",,", ",", -1))
	input.Set("uid", c.Qid)
	if input.Get("all") != "" {
		input.Del("all")
	}
	var uidArr []string
	uidArr = strings.Split(input.Get("user_group"), ",")
	extra := make(map[string]interface{})
	if input.Get("url") != "" {
		extra["url"] = input.Get("url")
	}
	if err := models.JPush(input.Get("content"), uidArr, extra); err != nil {
		c.Data["json"] = 0
		return
	} else {
		if res, err := models.Save("push_record", input); err != nil {
			beego.Debug(err)
			c.Data["json"] = 0
		} else {

			c.Data["json"] = 1
			var r models.Mt_systems_record
			r.Tid = int(res)
			if input.Get("id") == "" {
				r.Way = 2
			} else {
				r.Way = 3
			}
			r.Addtime = sword.Timeget()
			r.Table = 12
			r.Uid, _ = strconv.Atoi(c.Qid)
			if _, err := models.Orm().Insert(&r); err != nil {
				beego.Debug(err)
			}
		}
	}

}
